package com.alibaba.citrus.cr.sales.plan.facade.service.setting.contract;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.lock.RedisLock;
import com.alibaba.citrus.cr.common.model.ImportRequest;
import com.alibaba.citrus.cr.sales.plan.api.setting.contract.ContractFileService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.contract.CompanyContractImportRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.contract.ContractImportRequest;
import com.alibaba.citrus.cr.sales.plan.functions.contract.ContractAbility;
import com.alibaba.citrus.cr.sales.plan.model.enums.ContractDataSourceEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.ContractStatDimensionEnum;
import com.alibaba.citrus.cr.sales.plan.sdo.ContractSDO;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanOutCommonService;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.middleware.cache.runtime.service.EpochCacheService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.lattice2.epoch.user.dto.LoginUser;
import com.alibaba.lattice2.epoch.user.service.EpochLoginUserService;
import com.epoch.app.bcorder.contants.BcOrderConstants;
import com.epoch.app.bcorder.model.dto.EmployeeGetCurrentLoginResponse;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.sales_plan.contract.dto.DeleteContractsByConditionsRequest;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.api.group.scitemgroupquery.service.ScItemGroupQueryService;
import com.epoch.app.crplatformenhance.api.organizationquery.dto.GetOrganizationsByOutCodesRequest;
import com.epoch.app.crplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.crplatformenhance.dto.request.QueryScItemGroupRequest;
import com.epoch.app.crplatformenhance.dto.response.ScItemGroupResponse;
import com.epoch.app.crplatformenhance.model.dto.CustomerAddressIndex;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author luyi
 * @date 2021/11/1 4:25 下午
 */
@Component
public class ContractFileServiceImpl implements ContractFileService {

    private static final Log log = Log.getLogger(ContractFileServiceImpl.class);

    @Resource
    private ContractAbility contractAbility;

    @Resource
    private SalesPlanOutCommonService salesPlanOutCommonService;

    @Resource
    private CrPlatformEnhanceService crPlatformEnhanceService;

    @Resource
    private BcOrderService bcOrderService;

    private static final String key = "ContractFileService.customerImportHandle";

    @Resource
    private EpochCacheService epochCacheService;

    @Resource
    private OrganizationQueryService organizationQueryService;

    @Resource
    EpochLoginUserService epochLoginUserService;
    @Resource
    private ScItemGroupQueryService scItemGroupQueryService;
    @FacadeInvoker
    @Override
    public Result<List<ContractImportRequest>> customerImportHandle(List<ContractImportRequest> requestList) {
        if (CollectionUtils.isEmpty(requestList)) {
            return Result.success(Lists.newArrayList());
        }
        // 检查是否通过
        boolean importFlag = true;
        customerScaleProcess(requestList);
        Set<String> scItemSet = Sets.newHashSet();
        Set<String> customerAddressSet = Sets.newHashSet();
        Set<String> customerSet = Sets.newHashSet();
        Set<String> orgSalesOrganizationCodeSet = Sets.newHashSet();
        Set<String> channelCodeSet = Sets.newHashSet();
        Set<String> itemGroupSet = Sets.newHashSet();
        Set<String> contractYeaSet = Sets.newHashSet();
        Map<String,Integer> countMap = Maps.newHashMap();
        List<ContractImportRequest> requestList2 = Lists.newArrayList();
        List<ContractImportRequest> validRequestList = Lists.newArrayList();
        List<String> orgSalesOrganizationIdList = Lists.newArrayList();
        EmployeeGetCurrentLoginResponse currentLoginResponse = bcOrderService.employeeGetCurrentLogin();


        for (ContractImportRequest importRequest : requestList) {
            if (StringUtils.isBlank(importRequest.getContractYear())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-032", null).getDisplayErrorMessage());
                continue;
            }
            if (!Pattern.matches("^\\d{4}$", importRequest.getContractYear())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-15-014", null).getDisplayErrorMessage());
                continue;
            }
            if (StringUtils.isBlank(importRequest.getScItemId())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-026", null).getDisplayErrorMessage());
                continue;
            }
            if (StringUtils.isBlank(importRequest.getCustomerAddress())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-027", null).getDisplayErrorMessage());
                continue;
            }
            if (StringUtils.isBlank(importRequest.getCustomerCode())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-028", null).getDisplayErrorMessage());
                continue;
            }
            if (StringUtils.isBlank(importRequest.getOrgSalesOrganizationCode())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-029", null).getDisplayErrorMessage());
                continue;
            }
            if (StringUtils.isBlank(importRequest.getChannelCode())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-030", null).getDisplayErrorMessage());
                continue;
            }
            if (Objects.isNull(importRequest.getAnnualQuantity())){
                importRequest.setAnnualQuantity(0);
            }
            if (Objects.isNull(importRequest.getAnnualAmount())){
                importRequest.setAnnualAmount(0D);
            }
            if (Objects.isNull(importRequest.getAnnualTaxIncludedBeforeTax())){
                importRequest.setAnnualTaxIncludedBeforeTax(0D);
            }

            if (StringUtils.isBlank(importRequest.getItemGroup())){
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-031", null).getDisplayErrorMessage());
                continue;
            }
            Integer sumQuantity = getSumQuantity(importRequest.getJanQuantity(), importRequest.getFebQuantity(), importRequest.getMarQuantity(), importRequest.getAprQuantity(), importRequest.getMayQuantity(), importRequest.getJuneQuantity(), importRequest.getJulyQuantity(), importRequest.getAugQuantity(), importRequest.getSeptQuantity(), importRequest.getOctQuantity(), importRequest.getNovQuantity(), importRequest.getDecQuantity());

            if (!importRequest.getAnnualQuantity().equals(sumQuantity)){
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-006-00-16-018", null).getDisplayErrorMessage());
                continue;
            }

            BigDecimal sumBeforeDiscount = getBigDecimalOfZero(importRequest.getJanTaxIncludedBeforeTax(), importRequest.getFebTaxIncludedBeforeTax(), importRequest.getMarTaxIncludedBeforeTax(), importRequest.getAprTaxIncludedBeforeTax(), importRequest.getMayTaxIncludedBeforeTax(), importRequest.getJuneTaxIncludedBeforeTax(), importRequest.getJulyTaxIncludedBeforeTax(), importRequest.getAugTaxIncludedBeforeTax(), importRequest.getSeptTaxIncludedBeforeTax(), importRequest.getOctTaxIncludedBeforeTax(), importRequest.getNovTaxIncludedBeforeTax(), importRequest.getDecTaxIncludedBeforeTax());
            if (!sumBeforeDiscount.equals(BigDecimal.valueOf(importRequest.getAnnualTaxIncludedBeforeTax()).setScale(2,RoundingMode.HALF_UP)) ){
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-006-00-16-019", null).getDisplayErrorMessage());
                continue;
            }

            BigDecimal sumAmount = getBigDecimalOfZero(importRequest.getJanAmount(), importRequest.getFebAmount(), importRequest.getMarAmount(), importRequest.getAprAmount(), importRequest.getMayAmount(), importRequest.getJuneAmount(), importRequest.getJulyAmount(), importRequest.getAugAmount(), importRequest.getSeptAmount(), importRequest.getOctAmount(), importRequest.getNovAmount(), importRequest.getDecAmount());
            if (!sumAmount.equals(BigDecimal.valueOf(importRequest.getAnnualAmount()).setScale(2,RoundingMode.HALF_UP))){
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-006-00-16-020", null).getDisplayErrorMessage());
                continue;
            }

            scItemSet.add(importRequest.getScItemId());
            customerAddressSet.add(importRequest.getCustomerAddress());
            customerSet.add(importRequest.getCustomerCode());
            orgSalesOrganizationCodeSet.add(importRequest.getOrgSalesOrganizationCode());
            channelCodeSet.add(importRequest.getChannelCode());
            itemGroupSet.add(importRequest.getItemGroup());
            contractYeaSet.add(importRequest.getContractYear());
            String key = getUniqueKey(importRequest);
            countMap.put(key,countMap.get(key)==null ?1:countMap.get(key)+1);

            validRequestList.add(importRequest);
        }
        // 货品组
        Map<String, ScItemGroupResponse> productGroupMap = batchQueryProductGroup(itemGroupSet);

        for (ContractImportRequest contractImportRequest : validRequestList) {
            if (MapUtils.isEmpty(productGroupMap) || !productGroupMap.containsKey(StringUtils.trim(contractImportRequest.getItemGroup()))) {
                contractImportRequest.setErrorMessage("货品组无效");
                continue;
            }
            requestList2.add(contractImportRequest);

        }
        if (CollectionUtils.isEmpty(requestList2)) {
            return Result.success(requestList);
        }


        if (!"103".equals(currentLoginResponse.getRelatedOrganizationType())) {
            log.error("ContractFileServiceImpl.customerImportHandle.orgSalesOrganizationCodeResult nothingness");
            ImportRequest.setRequestErrorMessage(requestList2, ErrorMessage.code("OTS-01-004-02-16-023", null).getDisplayErrorMessage());
            return Result.fail(requestList,"OTS-01-004-02-16-023",ErrorMessage.code("OTS-01-004-02-16-023", null).getDisplayErrorMessage());
        }
        if (contractYeaSet.size() > 1){
            log.error("ContractFileServiceImpl.customerImportHandle contractYeaSet size > 0");
            ImportRequest.setRequestErrorMessage(requestList2, ErrorMessage.code("OTS-02-006-00-16-011", null).getDisplayErrorMessage());
            return Result.fail(requestList,"OTS-02-006-00-16-011", ErrorMessage.code("OTS-02-006-00-16-011", null).getDisplayErrorMessage());
        }
        if(orgSalesOrganizationCodeSet.size()> 1){
            log.error("ContractFileServiceImpl.customerImportHandle orgSalesOrganizationCodeSet size > 0");
            ImportRequest.setRequestErrorMessage(requestList2, ErrorMessage.code("OTS-02-006-00-16-012", null).getDisplayErrorMessage());
            return Result.fail(requestList,"OTS-02-006-00-16-012",ErrorMessage.code("OTS-02-006-00-16-012", null).getDisplayErrorMessage());
        }

        //销售组织外部编码 置换 内部ID
        Map<String, OrganizationSDO> organizationMapByOutCode = salesPlanOutCommonService.getOrganizationMapByOutCode(orgSalesOrganizationCodeSet);
        if (organizationMapByOutCode == null) {
            log.error("ContractFileServiceImpl.customerImportHandle.orgSalesOrganizationCodeResult nothingness");
            ImportRequest.setRequestErrorMessage(requestList2, ErrorMessage.code("OTS-01-005-02-15-006", null).getDisplayErrorMessage());
            return Result.fail(requestList,"OTS-01-005-02-15-006",ErrorMessage.code("OTS-01-005-02-15-006", null).getDisplayErrorMessage());
        }

        //货品外部code 置换 内部ID
        Map<String, ScItemSDO> scItemMap = salesPlanOutCommonService.getScItemMapByOutId(scItemSet);
        if (scItemMap == null) {
            log.error("ContractFileServiceImpl.customerImportHandle.scItemResult nothingness");
            ImportRequest.setRequestErrorMessage(requestList2, ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
            return Result.fail(requestList,"OTS-01-005-02-15-001", ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
        }
        //查询 客户地址 (五键唯一)
        Set<String> organizationIdList = organizationMapByOutCode.values().stream().map(OrganizationSDO::getId).collect(Collectors.toSet());
        Map<String, CustomerAddressIndex> customerAddressMap = salesPlanOutCommonService.getCustomerAddressByFive(customerAddressSet, customerSet, organizationIdList, channelCodeSet, itemGroupSet);
        if (customerAddressMap == null){
            ImportRequest.setRequestErrorMessage(requestList2, ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
            return Result.fail(requestList,"OTS-01-004-02-15-002",ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
        }

        List<ContractSDO> request = Lists.newArrayList();
        for (ContractImportRequest importRequest : requestList2) {
            String key = getUniqueKey(importRequest);
            if (countMap.get(key) > 1){
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-006-00-16-014", null).getDisplayErrorMessage());
                continue;
            }
            if (!Pattern.matches("^\\d{4}$", importRequest.getContractYear())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-15-014", null).getDisplayErrorMessage());
                continue;
            }
            OrganizationSDO organization = organizationMapByOutCode.get(importRequest.getOrgSalesOrganizationCode());
            if (organization == null) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-006", null).getDisplayErrorMessage());
                continue;
            }

            //客户编码 + 客户地址编码 + 销售组织编码（ID） + 业务渠道编码 + 货品组
            CustomerAddressIndex customerAddress = customerAddressMap.get(importRequest.getCustomerCode() + importRequest.getCustomerAddress() + organization.getId() + importRequest.getChannelCode() + importRequest.getItemGroup());

            if (customerAddress == null) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
                continue;
            }
            if (customerAddress.getStatus() == 0) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-007", null).getDisplayErrorMessage());
                continue;
            }

            if (!currentLoginResponse.getRelatedOrganizationId().equals(customerAddress.getOrgBussinessUnitCode())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-013", null).getDisplayErrorMessage());
                continue;
            }
            ScItemSDO scItem = scItemMap.get(importRequest.getScItemId());
            if (Objects.isNull(scItem)) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
                continue;
            }
            ContractSDO contract = getContractSDO(importRequest, customerAddress, scItem);
            orgSalesOrganizationIdList.add(contract.getOrgSalesOrganizationCode());
            request.add(contract);
        }

//       if (CollectionUtils.isNotEmpty(request)) {
//            Map<String, ContractSDO> contractMap = request.stream().collect(Collectors.toMap(contract -> SalesPlanCommonService.getCombinationKey(contract.getContractYear(), contract.getCustomerAddressId(), contract.getScItemId()), a -> a, (a, b) -> a));
//            List<ContractSDO> contractSDOList = new ArrayList<>(contractMap.values());

            if (CollectionUtils.isNotEmpty(request) && importFlag){
                StopWatch stopWatch = new StopWatch("ContractFileService.customerImportHandle");
                stopWatch.start();
                boolean bool = true;
                while (bool) {
                    try (RedisLock lock = new RedisLock(BcOrderConstants.REDIS_CACHE_CODE(), key)) {
                        boolean locked = lock.lock();
                        if (!locked) {
                            log.info("ContractFileService.customerImportHandle.batchCreateContract:获取锁失败");
                            continue;
                        }
                        // 销售组织维度删除历史数据
                        Integer integer = contractAbility.deleteContractByCondition(DeleteContractsByConditionsRequest.builder().contractYear(new ArrayList<String>(contractYeaSet).get(0)).orgSalesOrganizationCode(orgSalesOrganizationIdList.get(0)).type(ContractStatDimensionEnum.CUSTOMER_SC_ITEM.getCode()).build());
                        log.info("删除条数：{}",integer);
                        contractAbility.batchCreateContract(ContractStatDimensionEnum.CUSTOMER_SC_ITEM.getCode(), request);
                        // 封装回调函数中请求参数
                        Map<String,String> redisValue = new HashMap<>();
                        List<String> contractYearList = new ArrayList<>(contractYeaSet);
                        redisValue.put("contractYear",contractYearList.get(0));
                        List<String> orgSalesOrganizationCodeList = new ArrayList<>(orgSalesOrganizationCodeSet);
                        Result<List<OrganizationSDO>> organizationsByOutCodes = organizationQueryService.getOrganizationsByOutCodes(GetOrganizationsByOutCodesRequest.builder().outCodes(orgSalesOrganizationCodeList).build());
                        String orgSalesOrganizationCode = orgSalesOrganizationCodeList.get(0);
                        redisValue.put("organizationCode",orgSalesOrganizationCode);
                        List<String> list = new ArrayList<>();
                        list.add(orgSalesOrganizationCode);
                        redisValue.put("organizationName",organizationsByOutCodes.getTotal()==0?"":organizationsByOutCodes.getResult().get(0).getName());
                        // 1.客户合同量 2.公司合同量
                        redisValue.put("modelType","1");
                        LoginUser loginUser = epochLoginUserService.getLoginUser();
                        redisValue.put("operate",loginUser.getRealName());
                        epochCacheService.put(BcOrderConstants.REDIS_CACHE_CODE(), loginUser.getEmpId(),JSONObject.toJSONString(redisValue),5L, TimeUnit.SECONDS);
                        log.info("redis key:{},value:{}",loginUser.getEmpId(),JSONObject.toJSONString(redisValue));
                        bool = false;
                        stopWatch.stop();
                        log.info("ContractFileService.customerImportHandle.batchCreateContract:耗时" + stopWatch.getTotalTimeMillis() + "ms");
                        return Result.success(requestList);
                    } catch (Exception e) {
                        log.info("ContractFileService.customerImportHandle.batchCreateContract={}", JSONObject.toJSONString(e));
                        break;
                    }
                }
            }
//        }
        // 写入未导入数据为未导入，否则页面提示计数不正确
        requestList.forEach(e->{
            if(StringUtils.isEmpty(e.getErrorMessage())){
                e.setErrorMessage("未导入");
            }
        });
        return Result.fail(requestList,"","");
    }
    private Map<String, ScItemGroupResponse> batchQueryProductGroup(Set<String> productGroupCodeSet) {
        Map<String, ScItemGroupResponse> productGroupMap = Maps.newHashMap();
        for (String productGroup : productGroupCodeSet) {
            QueryScItemGroupRequest request = new QueryScItemGroupRequest();
            request.setCode(productGroup);
            Result<ScItemGroupResponse> result = scItemGroupQueryService.getScItemGroup(request);
            if (result != null && result.getResult() != null && StringUtils.isNotBlank(result.getResult().getCode())) {
                productGroupMap.put(productGroup, result.getResult());
            }
        }
        return productGroupMap;
    }
    @NotNull
    private String getUniqueKey(ContractImportRequest importRequest) {
        String key = importRequest.getContractYear() + "-" +
                importRequest.getOrgSalesOrganizationCode() + "-" +
                importRequest.getCustomerCode() + "-" +
                importRequest.getCustomerAddress() + "-" +
                importRequest.getChannelCode() + "-" +
                importRequest.getItemGroup() +
                "-" + importRequest.getScItemId();
        return key;
    }

    @NotNull
    private ContractSDO getContractSDO(ContractImportRequest importRequest, CustomerAddressIndex customerAddress, ScItemSDO scItem) {
        ContractSDO contract = new ContractSDO();
        BeanUtils.copyProperties(importRequest, contract);

        contract.setAnnualAmount(doubleToLong(importRequest.getAnnualAmount()));
        contract.setAnnualTaxIncludedBeforeTax(doubleToLong(importRequest.getAnnualTaxIncludedBeforeTax()));
        contract.setAprAmount(doubleToLong(importRequest.getAprAmount()));
        contract.setJanAmount(doubleToLong(importRequest.getJanAmount()));
        contract.setFebAmount(doubleToLong(importRequest.getFebAmount()));
        contract.setMarAmount(doubleToLong(importRequest.getMarAmount()));
        contract.setMayAmount(doubleToLong(importRequest.getMayAmount()));
        contract.setJuneAmount(doubleToLong(importRequest.getJuneAmount()));
        contract.setJulyAmount(doubleToLong(importRequest.getJulyAmount()));
        contract.setAugAmount(doubleToLong(importRequest.getAugAmount()));
        contract.setSeptAmount(doubleToLong(importRequest.getSeptAmount()));
        contract.setOctAmount(doubleToLong(importRequest.getOctAmount()));
        contract.setNovAmount(doubleToLong(importRequest.getNovAmount()));
        contract.setDecAmount(doubleToLong(importRequest.getDecAmount()));
        contract.setJanAfterDiscount(doubleToLong(importRequest.getJanAfterDiscount()));
        contract.setFebAfterDiscount(doubleToLong(importRequest.getFebAfterDiscount()));
        contract.setMarAfterDiscount(doubleToLong(importRequest.getMarAfterDiscount()));
        contract.setAprAfterDiscount(doubleToLong(importRequest.getAprAfterDiscount()));
        contract.setMayAfterDiscount(doubleToLong(importRequest.getMayAfterDiscount()));
        contract.setJuneAfterDiscount(doubleToLong(importRequest.getJuneAfterDiscount()));
        contract.setJulyAfterDiscount(doubleToLong(importRequest.getJulyAfterDiscount()));
        contract.setAugAfterDiscount(doubleToLong(importRequest.getAugAfterDiscount()));
        contract.setSeptAfterDiscount(doubleToLong(importRequest.getSeptAfterDiscount()));
        contract.setOctAfterDiscount(doubleToLong(importRequest.getOctAfterDiscount()));
        contract.setNovAfterDiscount(doubleToLong(importRequest.getNovAfterDiscount()));
        contract.setDecAfterDiscount(doubleToLong(importRequest.getDecAfterDiscount()));
        contract.setAnnualAfterDiscount(doubleToLong(importRequest.getAnnualAfterDiscount()));
        contract.setJanTaxIncludedBeforeTax(doubleToLong(importRequest.getJanTaxIncludedBeforeTax()));
        contract.setFebTaxIncludedBeforeTax(doubleToLong(importRequest.getFebTaxIncludedBeforeTax()));
        contract.setMarTaxIncludedBeforeTax(doubleToLong(importRequest.getMarTaxIncludedBeforeTax()));
        contract.setAprTaxIncludedBeforeTax(doubleToLong(importRequest.getAprTaxIncludedBeforeTax()));
        contract.setMayTaxIncludedBeforeTax(doubleToLong(importRequest.getMayTaxIncludedBeforeTax()));
        contract.setJuneTaxIncludedBeforeTax(doubleToLong(importRequest.getJuneTaxIncludedBeforeTax()));
        contract.setJulyTaxIncludedBeforeTax(doubleToLong(importRequest.getJulyTaxIncludedBeforeTax()));
        contract.setAugTaxIncludedBeforeTax(doubleToLong(importRequest.getAugTaxIncludedBeforeTax()));
        contract.setSeptTaxIncludedBeforeTax(doubleToLong(importRequest.getSeptTaxIncludedBeforeTax()));
        contract.setOctTaxIncludedBeforeTax(doubleToLong(importRequest.getOctTaxIncludedBeforeTax()));
        contract.setNovTaxIncludedBeforeTax(doubleToLong(importRequest.getNovTaxIncludedBeforeTax()));
        contract.setDecTaxIncludedBeforeTax(doubleToLong(importRequest.getDecTaxIncludedBeforeTax()));

        contract.setType(ContractStatDimensionEnum.CUSTOMER_SC_ITEM.getCode());
        contract.setDataSource(ContractDataSourceEnum.EXCEL.getCode());
        contract.setOrgBusinessUnitCode(customerAddress.getOrgBussinessUnitCode());
        contract.setOrgSalesOrganizationCode(customerAddress.getOrgSaleOrganizationCode());
        contract.setOrgSalesChannelCode(customerAddress.getOrgSaleChannelCode());
        contract.setOrgSalesDepartmentCode(customerAddress.getOrgSaleDepartmentCode());
        contract.setChannelCode(customerAddress.getChannelCode());
        contract.setCustomerCode(customerAddress.getCustomerCode());
        contract.setCustomerAddress(customerAddress.getAddressCode());
        contract.setManageEmployeeId(customerAddress.getPrincipal());
        contract.setCustomerAddressId(Objects.toString(customerAddress.getId(),null));

        contract.setScItemId(scItem.getScItemId());
        contract.setScItemCategoryId(scItem.getLeafCategoryId());
        return contract;
    }


    private int getSumQuantity(Integer importRequest, Integer importRequest1, Integer importRequest2, Integer importRequest3, Integer importRequest4, Integer importRequest5, Integer importRequest6, Integer importRequest7, Integer importRequest8, Integer importRequest9, Integer importRequest10, Integer importRequest11) {
        return Optional.ofNullable(importRequest).orElse(0)
                + Optional.ofNullable(importRequest1).orElse(0)
                + Optional.ofNullable(importRequest2).orElse(0)
                + Optional.ofNullable(importRequest3).orElse(0)
                + Optional.ofNullable(importRequest4).orElse(0)
                + Optional.ofNullable(importRequest5).orElse(0)
                + Optional.ofNullable(importRequest6).orElse(0)
                + Optional.ofNullable(importRequest7).orElse(0)
                + Optional.ofNullable(importRequest8).orElse(0)
                + Optional.ofNullable(importRequest9).orElse(0)
                + Optional.ofNullable(importRequest10).orElse(0)
                + Optional.ofNullable(importRequest11).orElse(0);
    }

    private void customerScaleProcess(List<ContractImportRequest> requestList) {
        requestList.forEach(o->{
            o.setAnnualAmount(doubleScaleProcess(o.getAnnualAmount()));
            o.setAnnualAfterDiscount(doubleScaleProcess(o.getAnnualAfterDiscount()));
            o.setAnnualTaxIncludedBeforeTax(doubleScaleProcess(o.getAnnualTaxIncludedBeforeTax()));

            o.setJanAmount(doubleScaleProcess(o.getJanAmount()));
            o.setJanAfterDiscount(doubleScaleProcess(o.getJanAfterDiscount()));
            o.setJanTaxIncludedBeforeTax(doubleScaleProcess(o.getJanTaxIncludedBeforeTax()));

            o.setFebAmount(doubleScaleProcess(o.getFebAmount()));
            o.setFebAfterDiscount(doubleScaleProcess(o.getFebAfterDiscount()));
            o.setFebTaxIncludedBeforeTax(doubleScaleProcess(o.getFebTaxIncludedBeforeTax()));

            o.setMarAmount(doubleScaleProcess(o.getMarAmount()));
            o.setMarAfterDiscount(doubleScaleProcess(o.getMarAfterDiscount()));
            o.setMarTaxIncludedBeforeTax(doubleScaleProcess(o.getMarTaxIncludedBeforeTax()));

            o.setAprAmount(doubleScaleProcess(o.getAprAmount()));
            o.setAprAfterDiscount(doubleScaleProcess(o.getAprAfterDiscount()));
            o.setAprTaxIncludedBeforeTax(doubleScaleProcess(o.getAprTaxIncludedBeforeTax()));

            o.setMayAmount(doubleScaleProcess(o.getMayAmount()));
            o.setMayAfterDiscount(doubleScaleProcess(o.getMayAfterDiscount()));
            o.setMayTaxIncludedBeforeTax(doubleScaleProcess(o.getMayTaxIncludedBeforeTax()));

            o.setJuneAmount(doubleScaleProcess(o.getJuneAmount()));
            o.setJuneAfterDiscount(doubleScaleProcess(o.getJuneAfterDiscount()));
            o.setJuneTaxIncludedBeforeTax(doubleScaleProcess(o.getJuneTaxIncludedBeforeTax()));

            o.setJulyAmount(doubleScaleProcess(o.getJulyAmount()));
            o.setJulyAfterDiscount(doubleScaleProcess(o.getJulyAfterDiscount()));
            o.setJulyTaxIncludedBeforeTax(doubleScaleProcess(o.getJulyTaxIncludedBeforeTax()));

            o.setAugAmount(doubleScaleProcess(o.getAugAmount()));
            o.setAugAfterDiscount(doubleScaleProcess(o.getAugAfterDiscount()));
            o.setAugTaxIncludedBeforeTax(doubleScaleProcess(o.getAugTaxIncludedBeforeTax()));

            o.setSeptAmount(doubleScaleProcess(o.getSeptAmount()));
            o.setSeptAfterDiscount(doubleScaleProcess(o.getSeptAfterDiscount()));
            o.setSeptTaxIncludedBeforeTax(doubleScaleProcess(o.getSeptTaxIncludedBeforeTax()));

            o.setOctAmount(doubleScaleProcess(o.getOctAmount()));
            o.setOctAfterDiscount(doubleScaleProcess(o.getOctAfterDiscount()));
            o.setOctTaxIncludedBeforeTax(doubleScaleProcess(o.getOctTaxIncludedBeforeTax()));

            o.setNovAmount(doubleScaleProcess(o.getNovAmount()));
            o.setNovAfterDiscount(doubleScaleProcess(o.getNovAfterDiscount()));
            o.setNovTaxIncludedBeforeTax(doubleScaleProcess(o.getNovTaxIncludedBeforeTax()));

            o.setDecAmount(doubleScaleProcess(o.getDecAmount()));
            o.setDecAfterDiscount(doubleScaleProcess(o.getDecAfterDiscount()));
            o.setDecTaxIncludedBeforeTax(doubleScaleProcess(o.getDecTaxIncludedBeforeTax()));

        });
    }

    @Override
    @FacadeInvoker
    public Result<List<CompanyContractImportRequest>> companyImportHandle(List<CompanyContractImportRequest> requestList) {
        if (CollectionUtils.isEmpty(requestList)) {
            return Result.success(Lists.newArrayList());
        }

        companyScaleProcess(requestList);
        EmployeeGetCurrentLoginResponse currentLoginResponse = bcOrderService.employeeGetCurrentLogin();
        if(!"103".equals(currentLoginResponse.getRelatedOrganizationType())){
            log.error("ContractFileServiceImpl.companyImportHandle.organizationMap no permissions");
            return Result.success(ImportRequest.setRequestErrorMessage(requestList, ErrorMessage.code("OTS-01-004-02-16-023", null).getDisplayErrorMessage()));
        }
        boolean importFlag = true;
        Set<String> contractYearSet = Sets.newHashSet();
        Set<String> organizationSet = Sets.newHashSet();
        Set<String> scItemSet = Sets.newHashSet();
        Map<String,Integer> countMap = Maps.newHashMap();
        List<String> organizationList = Lists.newArrayList();
        List<CompanyContractImportRequest> checkList = Lists.newArrayList();
        for (CompanyContractImportRequest importRequest : requestList) {
            //判空
            if (StringUtils.isBlank(importRequest.getContractYear())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-032", null).getDisplayErrorMessage());
                continue;
            }
            if (StringUtils.isBlank(importRequest.getOrgBusinessUnitCode())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-009", null).getDisplayErrorMessage());
                continue;
            }
            if (StringUtils.isBlank(importRequest.getScItemId())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-003", null).getDisplayErrorMessage());
                continue;
            }
            if (!Pattern.matches("^\\d{4}$", importRequest.getContractYear())) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-15-014", null).getDisplayErrorMessage());
                continue;
            }
            Integer sumQuantity = getSumQuantity(importRequest.getJanQuantity(), importRequest.getFebQuantity(), importRequest.getMarQuantity(), importRequest.getAprQuantity(), importRequest.getMayQuantity(), importRequest.getJuneQuantity(), importRequest.getJulyQuantity(), importRequest.getAugQuantity(), importRequest.getSeptQuantity(), importRequest.getOctQuantity(), importRequest.getNovQuantity(), importRequest.getDecQuantity());
            if (!importRequest.getAnnualQuantity().equals(sumQuantity)){
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-006-00-16-018", null).getDisplayErrorMessage());
                continue;
            }
            BigDecimal sumBeforeDiscount = getBigDecimalOfZero(importRequest.getJanTaxIncludedBeforeTax(), importRequest.getFebTaxIncludedBeforeTax(), importRequest.getMarTaxIncludedBeforeTax(), importRequest.getAprTaxIncludedBeforeTax(), importRequest.getMayTaxIncludedBeforeTax(), importRequest.getJuneTaxIncludedBeforeTax(), importRequest.getJulyTaxIncludedBeforeTax(), importRequest.getAugTaxIncludedBeforeTax(), importRequest.getSeptTaxIncludedBeforeTax(), importRequest.getOctTaxIncludedBeforeTax(), importRequest.getNovTaxIncludedBeforeTax(), importRequest.getDecTaxIncludedBeforeTax());
            if (!sumBeforeDiscount.equals(BigDecimal.valueOf(importRequest.getAnnualTaxIncludedBeforeTax()).setScale(2,RoundingMode.HALF_UP)) ){
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-006-00-16-019", null).getDisplayErrorMessage());
                continue;
            }

            BigDecimal sumAmount = getBigDecimalOfZero(importRequest.getJanAmount(), importRequest.getFebAmount(), importRequest.getMarAmount(), importRequest.getAprAmount(), importRequest.getMayAmount(), importRequest.getJuneAmount(), importRequest.getJulyAmount(), importRequest.getAugAmount(), importRequest.getSeptAmount(), importRequest.getOctAmount(), importRequest.getNovAmount(), importRequest.getDecAmount());
            if (!sumAmount.equals(BigDecimal.valueOf(importRequest.getAnnualAmount()).setScale(2,RoundingMode.HALF_UP))){
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-006-00-16-020", null).getDisplayErrorMessage());
                continue;
            }
            contractYearSet.add(importRequest.getContractYear());
            organizationSet.add(importRequest.getOrgBusinessUnitCode());
            scItemSet.add(importRequest.getScItemId());
            String key = new StringBuilder().append(importRequest.getContractYear()).append("-").append(importRequest.getOrgBusinessUnitCode()).append("-").append(importRequest.getScItemId()).toString();
            countMap.put(key,countMap.get(key)==null ?1:countMap.get(key)+1);
            checkList.add(importRequest);
        }
        if (CollectionUtils.isEmpty(checkList)){
            return Result.success(requestList);
        }
        if (contractYearSet.size() > 1){
            log.error("ContractFileServiceImpl.companyImportHandle contractYearSet size > 1");
            ImportRequest.setRequestErrorMessage(checkList, ErrorMessage.code("OTS-02-006-00-16-011", null).getDisplayErrorMessage());
            return Result.fail(requestList,"OTS-02-006-00-16-011",ErrorMessage.code("OTS-02-006-00-16-011",null).getDisplayErrorMessage());
        }

        if (organizationSet.size() > 1){
            log.error("ContractFileServiceImpl.companyImportHandle organizationSet size > 1");
            ImportRequest.setRequestErrorMessage(checkList, ErrorMessage.code("OTS-02-006-00-16-013", null).getDisplayErrorMessage());
            return Result.fail(requestList,"OTS-02-006-00-16-013",ErrorMessage.code("OTS-02-006-00-16-013",null).getDisplayErrorMessage());
        }


        Map<String, OrganizationSDO> organizationMap = salesPlanOutCommonService.getOrganizationMapByOutCode(organizationSet);
        if (organizationMap == null) {
            log.error("ContractFileServiceImpl.companyImportHandle.organizationMap nothingness");
            ImportRequest.setRequestErrorMessage(checkList, ErrorMessage.code("OTS-01-003-01-16-003", null).getDisplayErrorMessage());
            return Result.fail(requestList,"OTS-01-003-01-16-003",ErrorMessage.code("OTS-01-003-01-16-003",null).getDisplayErrorMessage());
        }
        Map<String, ScItemSDO> scItemMap = salesPlanOutCommonService.getScItemMapByOutId(scItemSet);
        if (scItemMap == null) {
            log.error("ContractFileServiceImpl.companyImportHandle.scItemMap nothingness");
            ImportRequest.setRequestErrorMessage(checkList, ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
            return Result.fail(requestList,"OTS-01-005-02-15-001",ErrorMessage.code("OTS-01-005-02-15-001",null).getDisplayErrorMessage());
        }
        Result<List<OrganizationSDO>> loginEmployeeBusinessUnit = crPlatformEnhanceService.getLoginEmployeeBusinessUnits();
        OrganizationSDO unit = new OrganizationSDO();
        if (Objects.nonNull(loginEmployeeBusinessUnit) && CollectionUtils.isNotEmpty(loginEmployeeBusinessUnit.getResult())) {
            unit = loginEmployeeBusinessUnit.getResult().get(0);
        }

        List<ContractSDO> request = Lists.newArrayList();
        for (CompanyContractImportRequest importRequest : checkList) {
            String key = new StringBuilder().append(importRequest.getContractYear()).append("-").append(importRequest.getOrgBusinessUnitCode()).append("-").append(importRequest.getScItemId()).toString();
            if (countMap.get(key) > 1){
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-02-006-00-16-017", null).getDisplayErrorMessage());
                continue;
            }
            OrganizationSDO organization = organizationMap.get(importRequest.getOrgBusinessUnitCode());
            if (Objects.isNull(organization)) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-003-01-16-003", null).getDisplayErrorMessage());
                continue;
            }
            if (organization.getType() != 103) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-003-01-15-011", null).getDisplayErrorMessage());
                continue;
            }
            if (!organization.getId().equals(unit.getId())) {
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-003-01-15-026", null).getDisplayErrorMessage());
                continue;
            }
            ScItemSDO scItem = scItemMap.get(importRequest.getScItemId());
            if (Objects.isNull(scItem)) {
                importFlag = false;
                importRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
                continue;
            }

            ContractSDO contract = new ContractSDO();
            BeanUtils.copyProperties(importRequest, contract);

            contract.setAnnualAmount(doubleToLong(importRequest.getAnnualAmount()));
            contract.setAnnualTaxIncludedBeforeTax(doubleToLong(importRequest.getAnnualTaxIncludedBeforeTax()));
            contract.setAprAmount(doubleToLong(importRequest.getAprAmount()));
            contract.setJanAmount(doubleToLong(importRequest.getJanAmount()));
            contract.setFebAmount(doubleToLong(importRequest.getFebAmount()));
            contract.setMarAmount(doubleToLong(importRequest.getMarAmount()));
            contract.setMayAmount(doubleToLong(importRequest.getMayAmount()));
            contract.setJuneAmount(doubleToLong(importRequest.getJuneAmount()));
            contract.setJulyAmount(doubleToLong(importRequest.getJulyAmount()));
            contract.setAugAmount(doubleToLong(importRequest.getAugAmount()));
            contract.setSeptAmount(doubleToLong(importRequest.getSeptAmount()));
            contract.setOctAmount(doubleToLong(importRequest.getOctAmount()));
            contract.setNovAmount(doubleToLong(importRequest.getNovAmount()));
            contract.setDecAmount(doubleToLong(importRequest.getDecAmount()));
            contract.setJanAfterDiscount(doubleToLong(importRequest.getJanAfterDiscount()));
            contract.setFebAfterDiscount(doubleToLong(importRequest.getFebAfterDiscount()));
            contract.setMarAfterDiscount(doubleToLong(importRequest.getMarAfterDiscount()));
            contract.setAprAfterDiscount(doubleToLong(importRequest.getAprAfterDiscount()));
            contract.setMayAfterDiscount(doubleToLong(importRequest.getMayAfterDiscount()));
            contract.setJuneAfterDiscount(doubleToLong(importRequest.getJuneAfterDiscount()));
            contract.setJulyAfterDiscount(doubleToLong(importRequest.getJulyAfterDiscount()));
            contract.setAugAfterDiscount(doubleToLong(importRequest.getAugAfterDiscount()));
            contract.setSeptAfterDiscount(doubleToLong(importRequest.getSeptAfterDiscount()));
            contract.setOctAfterDiscount(doubleToLong(importRequest.getOctAfterDiscount()));
            contract.setNovAfterDiscount(doubleToLong(importRequest.getNovAfterDiscount()));
            contract.setDecAfterDiscount(doubleToLong(importRequest.getDecAfterDiscount()));
            contract.setAnnualAfterDiscount(doubleToLong(importRequest.getAnnualAfterDiscount()));
            contract.setJanTaxIncludedBeforeTax(doubleToLong(importRequest.getJanTaxIncludedBeforeTax()));
            contract.setFebTaxIncludedBeforeTax(doubleToLong(importRequest.getFebTaxIncludedBeforeTax()));
            contract.setMarTaxIncludedBeforeTax(doubleToLong(importRequest.getMarTaxIncludedBeforeTax()));
            contract.setAprTaxIncludedBeforeTax(doubleToLong(importRequest.getAprTaxIncludedBeforeTax()));
            contract.setMayTaxIncludedBeforeTax(doubleToLong(importRequest.getMayTaxIncludedBeforeTax()));
            contract.setJuneTaxIncludedBeforeTax(doubleToLong(importRequest.getJuneTaxIncludedBeforeTax()));
            contract.setJulyTaxIncludedBeforeTax(doubleToLong(importRequest.getJulyTaxIncludedBeforeTax()));
            contract.setAugTaxIncludedBeforeTax(doubleToLong(importRequest.getAugTaxIncludedBeforeTax()));
            contract.setSeptTaxIncludedBeforeTax(doubleToLong(importRequest.getSeptTaxIncludedBeforeTax()));
            contract.setOctTaxIncludedBeforeTax(doubleToLong(importRequest.getOctTaxIncludedBeforeTax()));
            contract.setNovTaxIncludedBeforeTax(doubleToLong(importRequest.getNovTaxIncludedBeforeTax()));
            contract.setDecTaxIncludedBeforeTax(doubleToLong(importRequest.getDecTaxIncludedBeforeTax()));

            contract.setType(ContractStatDimensionEnum.COMPANY_SC_ITEM.getCode());
            contract.setDataSource(ContractDataSourceEnum.CRM.getCode());
            contract.setOrgBusinessUnitCode(organization.getId());

            contract.setScItemId(scItem.getScItemId());
            contract.setScItemCategoryId(scItem.getLeafCategoryId());
            organizationList.add(importRequest.getOrgBusinessUnitCode());

            request.add(contract);
        }
        if (request.size() >0 && importFlag){
            // 业务单元维度删除历史数据
            contractAbility.deleteContractByCondition(DeleteContractsByConditionsRequest.builder().contractYear(new ArrayList<String>(contractYearSet).get(0)).orgBusinessUnitCode(organizationMap.get(organizationList.get(0)).getId()).type(ContractStatDimensionEnum.COMPANY_SC_ITEM.getCode()).build());
            contractAbility.batchCreateContract(ContractStatDimensionEnum.COMPANY_SC_ITEM.getCode(), request);
            // 封装回调函数中请求参数
            Map<String,String> redisValue = new HashMap<>();
            List<String> contractYearList = new ArrayList<>(contractYearSet);
            redisValue.put("contractYear",contractYearList.get(0));
            List<String> organizationCodeList = new ArrayList<>(organizationSet);
            Result<List<OrganizationSDO>> organizationsByOutCodes = organizationQueryService.getOrganizationsByOutCodes(GetOrganizationsByOutCodesRequest.builder().outCodes(organizationCodeList).build());
            redisValue.put("organizationCode",organizationsByOutCodes.getTotal()==0?"":organizationsByOutCodes.getResult().get(0).getId());
            redisValue.put("organizationName",organizationsByOutCodes.getTotal()==0?"":organizationsByOutCodes.getResult().get(0).getName());
            // 1.客户合同量 2.公司合同量
            redisValue.put("modelType","2");
            LoginUser loginUser = epochLoginUserService.getLoginUser();
            redisValue.put("operate",loginUser.getRealName());
            epochCacheService.put(BcOrderConstants.REDIS_CACHE_CODE(), loginUser.getEmpId(),JSONObject.toJSONString(redisValue),5L, TimeUnit.SECONDS);
            log.info("redis key:{},value:{}",loginUser.getEmpId(),JSONObject.toJSONString(redisValue));
            return Result.success(requestList);
        }
        // 写入未导入数据为未导入，否则页页面提示部分导入计数不正确
        requestList.forEach(e->{
            if(StringUtils.isEmpty(e.getErrorMessage())){
                e.setErrorMessage("未导入");
            }
        });
        return Result.fail(requestList,"","");
    }

    private void companyScaleProcess(List<CompanyContractImportRequest> requestList) {
        requestList.forEach(o->{
            o.setAnnualAmount(doubleScaleProcess(o.getAnnualAmount()));
            o.setAnnualAfterDiscount(doubleScaleProcess(o.getAnnualAfterDiscount()));
            o.setAnnualTaxIncludedBeforeTax(doubleScaleProcess(o.getAnnualTaxIncludedBeforeTax()));

            o.setJanAmount(doubleScaleProcess(o.getJanAmount()));
            o.setJanAfterDiscount(doubleScaleProcess(o.getJanAfterDiscount()));
            o.setJanTaxIncludedBeforeTax(doubleScaleProcess(o.getJanTaxIncludedBeforeTax()));

            o.setFebAmount(doubleScaleProcess(o.getFebAmount()));
            o.setFebAfterDiscount(doubleScaleProcess(o.getFebAfterDiscount()));
            o.setFebTaxIncludedBeforeTax(doubleScaleProcess(o.getFebTaxIncludedBeforeTax()));

            o.setMarAmount(doubleScaleProcess(o.getMarAmount()));
            o.setMarAfterDiscount(doubleScaleProcess(o.getMarAfterDiscount()));
            o.setMarTaxIncludedBeforeTax(doubleScaleProcess(o.getMarTaxIncludedBeforeTax()));

            o.setAprAmount(doubleScaleProcess(o.getAprAmount()));
            o.setAprAfterDiscount(doubleScaleProcess(o.getAprAfterDiscount()));
            o.setAprTaxIncludedBeforeTax(doubleScaleProcess(o.getAprTaxIncludedBeforeTax()));

            o.setMayAmount(doubleScaleProcess(o.getMayAmount()));
            o.setMayAfterDiscount(doubleScaleProcess(o.getMayAfterDiscount()));
            o.setMayTaxIncludedBeforeTax(doubleScaleProcess(o.getMayTaxIncludedBeforeTax()));

            o.setJuneAmount(doubleScaleProcess(o.getJuneAmount()));
            o.setJuneAfterDiscount(doubleScaleProcess(o.getJuneAfterDiscount()));
            o.setJuneTaxIncludedBeforeTax(doubleScaleProcess(o.getJuneTaxIncludedBeforeTax()));

            o.setJulyAmount(doubleScaleProcess(o.getJulyAmount()));
            o.setJulyAfterDiscount(doubleScaleProcess(o.getJulyAfterDiscount()));
            o.setJulyTaxIncludedBeforeTax(doubleScaleProcess(o.getJulyTaxIncludedBeforeTax()));

            o.setAugAmount(doubleScaleProcess(o.getAugAmount()));
            o.setAugAfterDiscount(doubleScaleProcess(o.getAugAfterDiscount()));
            o.setAugTaxIncludedBeforeTax(doubleScaleProcess(o.getAugTaxIncludedBeforeTax()));

            o.setSeptAmount(doubleScaleProcess(o.getSeptAmount()));
            o.setSeptAfterDiscount(doubleScaleProcess(o.getSeptAfterDiscount()));
            o.setSeptTaxIncludedBeforeTax(doubleScaleProcess(o.getSeptTaxIncludedBeforeTax()));

            o.setOctAmount(doubleScaleProcess(o.getOctAmount()));
            o.setOctAfterDiscount(doubleScaleProcess(o.getOctAfterDiscount()));
            o.setOctTaxIncludedBeforeTax(doubleScaleProcess(o.getOctTaxIncludedBeforeTax()));

            o.setNovAmount(doubleScaleProcess(o.getNovAmount()));
            o.setNovAfterDiscount(doubleScaleProcess(o.getNovAfterDiscount()));
            o.setNovTaxIncludedBeforeTax(doubleScaleProcess(o.getNovTaxIncludedBeforeTax()));

            o.setDecAmount(doubleScaleProcess(o.getDecAmount()));
            o.setDecAfterDiscount(doubleScaleProcess(o.getDecAfterDiscount()));
            o.setDecTaxIncludedBeforeTax(doubleScaleProcess(o.getDecTaxIncludedBeforeTax()));

        });
    }

    private Double doubleScaleProcess(Double d){
        if(d == null){
            return null;
        }
        return BigDecimal.valueOf(d).setScale(2, RoundingMode.HALF_UP).doubleValue();
    }

    private Long doubleToLong(Double d) {
        if (d == null) {
            return 0L;
        }
        return BigDecimal.valueOf(d).multiply(new BigDecimal(100)).longValue();
    }


    @NotNull
    private BigDecimal getBigDecimalOfZero(Double importRequest, Double importRequest1, Double importRequest2, Double importRequest3, Double importRequest4, Double importRequest5, Double importRequest6, Double importRequest7, Double importRequest8, Double importRequest9, Double importRequest10, Double importRequest11) {
        return getBigDecimalOfZero(importRequest)
                .add(getBigDecimalOfZero(importRequest1))
                .add(getBigDecimalOfZero(importRequest2))
                .add(getBigDecimalOfZero(importRequest3))
                .add(getBigDecimalOfZero(importRequest4))
                .add(getBigDecimalOfZero(importRequest5))
                .add(getBigDecimalOfZero(importRequest6))
                .add(getBigDecimalOfZero(importRequest7))
                .add(getBigDecimalOfZero(importRequest8))
                .add(getBigDecimalOfZero(importRequest9))
                .add(getBigDecimalOfZero(importRequest10))
                .add(getBigDecimalOfZero(importRequest11))
                .setScale(2,RoundingMode.HALF_UP);
    }

    @NotNull
    private BigDecimal getBigDecimalOfZero(Double importRequest) {
        return new BigDecimal(Optional.ofNullable(importRequest).orElse(0D).toString());
    }
}
